package fr.smile.liferay.portlet.news.util;

import com.liferay.portal.kernel.exception.PortalException;
import com.liferay.portal.kernel.exception.SystemException;
import com.liferay.portal.security.auth.PrincipalException;
import com.liferay.portal.security.permission.PermissionChecker;
import com.liferay.portlet.announcements.model.AnnouncementsEntry;
import com.liferay.portlet.announcements.service.AnnouncementsEntryLocalServiceUtil;

import fr.smile.liferay.portlet.news.model.NewsEntry;
import fr.smile.liferay.portlet.news.service.NewsEntryLocalServiceUtil;

public class NewsletterEntryPermission {

	public static void check(
			PermissionChecker permissionChecker, NewsEntry entry,
			String actionId)
		throws PortalException {

		if (!contains(permissionChecker, entry, actionId)) {
			throw new PrincipalException();
		}
	}

	public static void check(
			PermissionChecker permissionChecker, long entryId, String actionId)
		throws PortalException, SystemException {

		if (!contains(permissionChecker, entryId, actionId)) {
			throw new PrincipalException();
		}
	}

	public static boolean contains(
		PermissionChecker permissionChecker, NewsEntry entry,
		String actionId) {

		if (permissionChecker.hasOwnerPermission(
				entry.getCompanyId(), NewsEntry.class.getName(),
				entry.getEntryId(), entry.getUserId(), actionId)) {

			return true;
		}

		return permissionChecker.hasPermission(
			0, AnnouncementsEntry.class.getName(), entry.getEntryId(),
			actionId);
	}

	public static boolean contains(
			PermissionChecker permissionChecker, long entryId, String actionId)
		throws PortalException, SystemException {

		NewsEntry entry = NewsEntryLocalServiceUtil.getNewsEntry(
			entryId);

		return contains(permissionChecker, entry, actionId);
	}

}